// pages/seaccounts/index.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    radio: '2',
    values: '',
    orderId: '121212',
    ///地址信息
    addli: '',
    arr: [],
    goodslist: [{
      goodId: '',
      goodsPrice: '',
      num: '',
      totalPrice: ''
    }],
   
    sum: 0,
    allsum:0,
    allsumss:0,
    type: 0,
    payPassnu: 0,
    orderId: 0,
    showPayPwdInput: false, //是否展示密码输入层
    pwdVal: '', //输入的密码
    payFocus: true, //文本框焦点
    Loadingtime: '',
    upgradeLevel:0,//晋级要的钱
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    // let obj=JSON.parse(options.data)
    // this.setData({
    //   addli:obj
    // })
    // const eventChannel = this.getOpenerEventChannel();
	
    options.arr = decodeURIComponent(options.arr);
    console.log(JSON.parse(options.arr));
    console.log(options.sum);
    console.log(options.type);
    console.log(options.upgradeLevel);
    this.setData({
      arr: JSON.parse(options.arr),
      sum: JSON.parse(options.sum),
      type: JSON.parse(options.type),
      upgradeLevel:JSON.parse(options.upgradeLevel)
    })
    //整理数据提交
    let allarr=this.data.arr
    let result = [];//结果保存
    console.log(this.data.arr);
    var allsums=0
    for (let i = 0; i <allarr.length; i++) {
      delete allarr[i].coverPic;
      delete allarr[i].goodAreaDetail;
      delete allarr[i].level;
      delete allarr[i].name;
      delete allarr[i].oldpric;
      allarr[i].goodId=allarr[i].id
      allarr[i].num=allarr[i].num
      allarr[i].goodsPrice=allarr[i].oldPrice*allarr[i].num
      allarr[i].totalPrice=allarr[i].price*allarr[i].num
      //计算总原价
      allsums+=allarr[i].goodsPrice
       //获取到list的第i个对象，修改后返回一个新对象，不修改原对象
       var resss = JSON.parse(JSON.stringify(allarr[i]).replace(/goodId/g, 'goodId').replace(/quantity/g, "num"));
       console.log(resss);
       result.push(resss)
       this.data.goodslist=result
     
    }
    this.data.allsumss=allsums
    console.log(result,allsums);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  /**
   * 显示支付密码输入层
   */
  showInputLayer() {
    this.setData({
      showPayPwdInput: true,
      payFocus: true
    });
  },
  /**
   * 隐藏支付密码输入层
   */
  hidePayLayer() {
    var val = this.data.pwdVal;
    this.setData({
      showPayPwdInput: false,
      payFocus: false,
      pwdVal: val
    }, );
    if (this.data.pwdVal) {
      wx.request({
        url: app.globalData.url+'/zkxj/order/wechat/integral/pay',
        data: {
          "orderId": this.data.orderId,
          "payPass": this.data.pwdVal
        },
        method: 'POST',
        header: {
         'content-type': 'application/json',
        'token':wx.getStorageSync('token')
        },
        success: (res) => {
          console.log(res.data.code);
          if (res.data.code == 0) {
            // 定时三秒跳转对比页面
            wx.showToast({
              title: '支付成功',
              icon: 'success',
              duration: 2000,
              mask: true
            })
            this.setData({
              Loadingtime: setInterval(function () {
                wx.redirectTo({
                  url: '/pages/orderform/index',
                })
              }, 2000)
            })

          }else if(res.data.code==500){
            wx.showToast({
              title: '支付密码错误',
              icon: 'error',
              duration: 2000,
              mask: true
            })
          }
        },

        // "fail": function (res) {
        //   wx.showToast({
        //     title: '失败',
        //     icon: 'error',
        //     duration: 1000,
        //     mask: true
        //   })
        // },
        // "complete": function (res) {
        //   wx.showToast({
        //     title: '取消',
        //     icon: 'error',
        //     duration: 1000,
        //     mask: true
        //   })
        // }

      })
    }
  },
  /**
   * 获取焦点
   */
  getFocus: function () {
    this.setData({
      payFocus: true
    });
  },
  /**
   * 输入密码监听
   */
  inputPwd: function (e) {
    this.setData({
      pwdVal: e.detail.value
    });

    if (e.detail.value.length >= 6) {
      this.hidePayLayer();
    }
  },
  postMoney() { // 点击确认充值
    // wx.showLoading({
    //   title: '加载中',
    // })
    let usid = wx.getStorageSync('userId')
    console.log(this.data.addli);
    if (!this.data.addli) {
      wx.showToast({
        title: '请填写地址',
        icon: 'error',
        duration: 1000,
        mask: true
      })
    } else {
      console.log(this.data.goodslist,this.data.allsumss);
      wx.request({
        url: app.globalData.url+'/zkxj/order/wechat/place',
        data: {
          "address": this.data.addli.address,
          "expressPrice": 0,
          // "openid":'',
          "goodList":  this.data.goodslist,
          "area": this.data.addli.area,
          "mobile": this.data.addli.mobile,
          "name": this.data.addli.name,
          "orderType": this.data.type,
          "payPrice": this.data.sum,
          // this.data.sum
          "payType": 2,
          "shopId": 0,
          // this.data.sum
          "upgradeLevel": this.data.upgradeLevel,
          "totalPrice": this.data.allsumss,
          "userId": usid,
        },
        method: 'POST',
        header: {
         'content-type': 'application/json',
        'token':wx.getStorageSync('token')
        },
        success: (res) => {
          if (res.data.code == 0) {
            if (res.data.data.orderId) {
              //调取键盘
              this.setData({
                showPayPwdInput: true,
                payFocus: true,
                orderId: res.data.data.orderId
              });
            }
          } else if (res.data.code == 500) {
            if(res.data.msg=="积分不足"){
              wx.showToast({
                title: "积分不足",
                icon: 'error',
                duration: 1000,
                mask: true
              })
            }else{

              wx.showToast({
                title: "未设置支付密码",
                icon: 'error',
                duration: 1000,
                mask: true
              })
              this.setData({
                Loadingtime: setInterval(function () {
                  wx.redirectTo({
                    url: '/pages/paypass/index',
                  })
                }, 1000)
              })
            }
          }
          // wx.requestPayment({ // 这一步是调起微信支付
          //   "appId": res.data.data.appId,
          //   "timeStamp": res.data.data.timestamp,
          //   "nonceStr": res.data.data.noncestr,
          //   "package": res.data.data.packageValue,
          //   "signType": "RSA",
          //   "paySign": res.data.data.paySign,
          //   "success": function (res) {

          //     console.log(res);
          //     wx.hideLoading({})
          //     if(res.errMsg){
          //       wx.navigateTo({
          //         url: '/pages/orderform/index',
          //       })
          //     }
          //     wx.showToast({
          //       title: '成功',
          //       icon: 'success',
          //       duration: 1000,
          //       mask: true
          //     })
          //   },
          //   "fail": function (res) {
          //     wx.showToast({
          //       title: '失败',
          //       icon: 'error',
          //       duration: 1000,
          //       mask: true
          //     })
          //   },
          //   // "complete": function (res) {
          //   //   wx.showToast({
          //   //     title: '取消',
          //   //     icon: 'error',
          //   //     duration: 1000,
          //   //     mask: true
          //   //   })
          //   // }
          // })
        },
      })

    }


  },
  //跳转收获地址页面
  handletosaddpage() {
    wx.navigateTo({
      url: '/pages/addlist/index',
    })
  },
  onChanges(event) {
    // event.detail 为当前输入的值
    // console.log(event.detail.value);
  },
  onChange(event) {
    this.setData({
      radio: event.detail,
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 关闭当前页面时取消定时器
    clearInterval(this.data.Loadingtime);
    // 页面接收值，在A页面的data里面自定义mydata接收值
    // 获取到上一页返回回来带的值
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1];
    var data = currPage.data.data
    this.setData({
      addli: JSON.parse(data)
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // 关闭当前页面时取消定时器
    clearInterval(this.data.Loadingtime);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 关闭当前页面时取消定时器
    clearInterval(this.data.Loadingtime);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})